package com.os.sys.controller.filter;

import com.alibaba.fastjson.JSON;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import util.JwtUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

/***************
 * token验证拦截
 * @author bamboo zjcjava@163.com
 * @time 2017-08-01
 */
@Component
@Slf4j
//@WebFilter(urlPatterns = { "/api/v/*" }, filterName = "tokenAuthorFilter")
public class AuthFilter implements Filter {

    @Autowired
    //@Lazy
    private JwtUtil jwtUtil;

    private static Logger logger = LoggerFactory
            .getLogger(AuthFilter.class);

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        //jwtUtil = new JwtUtil();
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse rep = (HttpServletResponse) response;

        //设置允许跨域的配置
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers","token,Origin, X-Requested-With, Content-Type, Accept");


        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        //((HttpServletResponse) response).setHeader("Access-Control-Allow-Origin", "*");
        String token = req.getHeader("token");//header方式
        //token = req.getHeader("easy-mock_token");
        //System.out.println("easy-mock_token = "+req.getCookies());
        Cookie[] cookies = req.getCookies();
        if(cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                System.out.println("cookie[" + i + "] =  " + cookies[i].getName() + "," + cookies[i].getValue());
                String name = cookies[i].getName();
                if (name.equalsIgnoreCase("token")) {
                    System.out.println("token = " + cookies[i].getValue());
                    token = cookies[i].getValue();
                }
            }
        }

        Result resultInfo = new Result();
        boolean isFilter = false;


        String method = ((HttpServletRequest) request).getMethod();
        System.out.println("method "+method);
        if (method.equals("OPTIONS")) {
            rep.setStatus(HttpServletResponse.SC_OK);
        }else{
            if (null == token || token.isEmpty()) {
                resultInfo.setCode(StatusCode.ACCESSERROR);
                resultInfo.setMessage("用户授权认证没有通过!客户端请求参数中无token信息");
            } else {
//                log.info("AuthFileter jwtUtil = "+jwtUtil);
//                if(jwtUtil!=null){
//                    log.info("AuthFileter jwtUtil.key = "+jwtUtil.getKey());
//                }
                jwtUtil = new JwtUtil();
                //这两个常量值应该从配置文件中提取,但jwtUtil不能正常注入，待解决-todo
                jwtUtil.setKey("itcast");
                jwtUtil.setTtl(3600000);
                System.out.println("jwtUtil = "+jwtUtil);
                Claims claims = jwtUtil.parseJWT(token);
                log.info("claims = ", claims);
                String roles = (String) claims.get("roles");
                log.info("claims.sub = "+claims.get("sub"));
                String subject = (String)claims.get("sub");
                //如果解析到账号，则认为是合法的
                if(StringUtils.isNotBlank(subject)){
                    resultInfo.setCode(StatusCode.OK);
                    resultInfo.setMessage("用户授权认证通过!");
                    log.info("用户["+subject+"]授权认证通过!");
                    isFilter = true;
                } else {
                    resultInfo.setCode(StatusCode.ACCESSERROR);
                    resultInfo.setMessage("用户授权认证没有通过!客户端请求参数token信息无效");
                }
            }
            if (resultInfo.getCode() == StatusCode.ACCESSERROR) {// 验证失败
                PrintWriter writer = null;
                OutputStreamWriter osw = null;
                try {
                    osw = new OutputStreamWriter(response.getOutputStream(),
                            "UTF-8");
                    writer = new PrintWriter(osw, true);
                    String jsonStr = JSON.toJSONString(resultInfo);
                    writer.write(jsonStr);
                    writer.flush();
                    writer.close();
                    osw.close();
                } catch (UnsupportedEncodingException e) {
                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
                } catch (IOException e) {
                    logger.error("过滤器返回信息失败:" + e.getMessage(), e);
                } finally {
                    if (null != writer) {
                        writer.close();
                    }
                    if (null != osw) {
                        osw.close();
                    }
                }
                return;
            }

            if (isFilter) {
                logger.info("token filter过滤ok!");
                chain.doFilter(request, response);
            }
        }


    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}
